const express = require('express');
const { readFileSync } = require('fs');
const fs = require('fs')
const path = require('path');
const url = require('url');
const multer = require('multer')
const { exec } = require('child_process');
const { videoTools } = require('./utils/index.js')
const dirname = process.cwd()
const app = express();
app.use(express.json())
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(process.cwd(), '/uploads'))
    },
    filename: function (req, file, cb) {
        cb(null, `${req.body.index}-${req.body.name}`)
    }
})

const uploadConfig = multer({ storage })

const upload = app.post('/tools/upload', uploadConfig.single('file'), (req, res) => {
    res.send({
        code: 200,
        data: req.file
    })
})

const zip = () => app.post('/tools/zip', (req, res) => {
    console.log('==============-------------------===============')
    const { name ,quality} = req.body
    const inputPath = path.join(dirname, 'files/', name);
    const outputPath = path.join(dirname, 'files/', name);
    const command = `pngquant ${inputPath} --speed=1 --quality=${quality||80} --force -o ${outputPath}`;
    const stdio = { stdio: 'inherit' }
    exec(command,stdio, (error, stdout, stderr) => {
        if (error) {
            return reject('压缩失败')
        }
        fs.readFile(outputPath, (err, data) => {
            if (err) {
                return reject('读取失败')
            }
            res.setHeader('Content-Type', 'application/json');
            res.statusCode = 200;
            // 图片转base64
            const base64 = Buffer.from(data).toString('base64');
            const buffer = Buffer.from(base64, 'base64');
            res.send(JSON.stringify({
                code: 200,
                msg: '成功',
                data: {
                    pic: base64,
                    compressSize: buffer.byteLength
                }
            }));
            fs.unlinkSync(outputPath);
        });
    });
})

// 合并文件
const merge = app.post('/tools/merge', (req, res) => {
    // 读取uploads下的所有文件
    const originFileName = req.body.name
    const dirPath = path.join(dirname, 'uploads/')
    const files = fs.readdirSync(dirPath);

    const sortedFiles = files.sort((a, b) => {
        const aIndex = parseInt(a.split('-')[0]);
        const bIndex = parseInt(b.split('-')[0]);
        return aIndex - bIndex;
    });
    // 合并文件
    const filepath = path.join(dirname, '/files', originFileName);
    sortedFiles.forEach(item => {
        const inputPath = path.join(dirPath, item);
        const file = readFileSync(inputPath)
        fs.appendFileSync(filepath, file)
        fs.unlinkSync(inputPath)
    })

    res.json({
        code: 200,
        msg: '合并成功',
        data: {}
    })
})

const editVideo = app.post('/tools/editVideo', async (req, res) => {
    const result = await videoTools(req.body)
    res.json({
        msg: '编辑成功',
        code: 200,
        data: {
            name: result
        }
    })
})

const downloadFile = app.post('/tools/download', (req, res) => {
    const filePath = path.join(process.cwd(), '/router/tools/files/', req.body.name)
    const fileStream = fs.readFileSync(filePath);
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Content-Disposition', `attachment; filename=${encodeURIComponent(req.body.name)}`);
    res.send(fileStream)
    fs.unlinkSync(filePath)
})

// export { upload, merge ,editVideo,downloadFile}
module.exports = { upload, merge, editVideo, downloadFile,zip }